<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>

    </style>
</head>

<body>
    <div id="app">
        <ul>
            <li v-for="(item, index) in list">
                <img style="width: 100px; height: 100px" :src="item.img" alt="">
                {{ item.title }}
                <button @click="delCount(index)">--</button>
                <span>
                    {{ item.count }}
                </span>
                <button @click="addCount(index)">+</button>
                <p>
                    价格: {{ item.price }}
                </p>
            </li>
        </ul>
        <h3>
            {{ allPrice.toFixed(2) }}
        </h3>
    </div>

    <script src="./js/vue.js"></script>
    <script>
        const app = new Vue({
            el: "#app",
            data: {
                list: [
                    {
                        img: "https://img0.baidu.com/it/u=1835573181,1800566933&fm=253&fmt=auto&app=120&f=JPEG?w=667&h=500",
                        title: "商品1",
                        count: 1,
                        price: 20.1
                    },
                    {
                        img: "https://t7.baidu.com/it/u=898806292,653496422&fm=193&f=GIF",
                        title: "商品2",
                        count: 1,
                        price: 30.1
                    },
                    {
                        img: "https://ns-strategy.cdn.bcebos.com/ns-strategy/upload/fc_big_pic/part-00302-80.jpg",
                        title: "商品3",
                        count: 1,
                        price: 10.1
                    }
                ],
            },
            methods: {
                addCount(index) {
                    this.list[index].count += 1
                },
                delCount(index) {
                    if (this.list[index].count === 1) {
                        // 删除splice(下标，个数)
                        this.list.splice(index, 1)
                    } else {
                        this.list[index].count -= 1
                    }
                }
            },
            computed: {
                allPrice({ list }) {
                    return list.reduce((prev, next) => {
                        return prev + next.count * next.price
                    }, 0)
                }
            }
        })

        // reduce(callback, 初始值)
        
    </script>
</body>

</html>